package com.study_security.controller;

import com.study_security.domain.LoginUser;
import com.study_security.domain.ResponseResult;
import com.study_security.dto.MemberDTO;
import com.study_security.dto.ProjectDTO;
import com.study_security.dto.TaskDTO;
import com.study_security.dto.UserDTO;
import com.study_security.entity.Project;
import com.study_security.entity.Task;
import com.study_security.mapper.UserMapper;
import com.study_security.service.ProjectService;
import com.study_security.service.TaskService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.study_security.utils.RedisConstants.PROJECT_KEY;

@RestController
@RequestMapping("/api/tasks")
//@PreAuthorize("hasAnyAuthority('perm_review','perm_leader','perm_member')")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProjectService projectService;

    /**
     * 根据项目名查找项目下的所有任务
     *
     * @param projectName 项目名
     * @return 项目下的所有任务
     */
    @GetMapping("/search")
    public List<TaskDTO> getTasksByProjectName(@RequestParam String projectName) {
        return taskService.getTasksByProjectName(projectName);
    }

    /**
     * 根据项目ID获取项目下的所有任务
     *
     * @param projectId 项目ID
     * @return 项目下的所有任务
     */
    @GetMapping("/project/{projectId}/tasks")   // /project/1/...
    public List<TaskDTO> getProjectTasks(@PathVariable Long projectId) {
        return taskService.getTasksByProjectId(projectId);
    }

    /**
     * 获取用户参与的所有项目
     *
     * @param authentication
     * @return 用户参与的所有项目
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @GetMapping("/projects")
    public List<ProjectDTO> getUserProjects(Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        return taskService.selectUserProjects(userId);
    }

    /**
     * 添加新任务
     *
     * @param task 任务信息
     * @return 添加任务结果
     */
    @PreAuthorize("hasAuthority('perm_leader')")
    @PostMapping("/add")
    public ResponseEntity<String> addTask(@RequestBody Task task) {
        boolean isAdded = taskService.addTask(task);
        return isAdded ? ResponseEntity.ok("任务添加成功！") :
                ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务添加失败。");
    }

    /**
     * 更新任务状态
     *
     * @param taskId 任务ID
     * @param authentication
     * @return 更新任务结果
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @PutMapping("/update/{taskId}")
    public ResponseEntity<String> updateTaskStatus(@PathVariable Long taskId,
                                                   @RequestParam BigDecimal workHours,
                                                   Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        UserDTO userDTO = userMapper.selectUserInfoById(userId);
        String userRole = userDTO.getUserRole();

        Task task = taskService.getTaskById(taskId);
        Integer projectId = task.getProjectId();
        Project projectById = projectService.getProjectById(Long.valueOf(projectId));
        Long responsibleId = projectById.getResponsibleId();
        if (task == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("任务不存在。");
        }

        // 检查是否是任务的负责人，或者项目负责人
        boolean isLeader = "项目负责人".equals(userRole);
        boolean isAssignedUser = Objects.equals(task.getAssignedToId(), userId);

        if (!isLeader && !isAssignedUser) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("您无权修改该任务。");
        }

        // 如果是成员提交任务，更新工时并设置为待审核
        if (isAssignedUser) {
            task.setWorkHours(workHours);  // 设置成员提交的工时
            LocalDateTime currentDate = LocalDateTime.now();
            Date endDate = Date.from(currentDate.atZone(ZoneId.systemDefault()).toInstant());
            task.setEndDate(endDate);
            task.setTaskStatus("待审核");  // 设置状态为待审核
            boolean isUpdated = taskService.updateTask(task);
            if(isUpdated){
                stringRedisTemplate.delete(PROJECT_KEY+responsibleId);
            }
            return isUpdated ? ResponseEntity.ok("任务提交成功，等待审核！")
                    : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务提交失败。");
        }
        // 如果是组长审核任务
        else if (isLeader) {

            // 更新任务状态
            task.setWorkHours(workHours);  // 设置成员提交的工时
            task.setTaskStatus("已审核");  // 通过枚举类型设置任务状态
            boolean isUpdated = taskService.updateTask(task);
            return isUpdated ? ResponseEntity.ok("任务状态更新成功！")
                    : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务状态更新失败。");
        } else {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无权执行此操作。");
        }
    }

//    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
//    @PutMapping("/update/{taskId}")
//    public ResponseEntity<String> updateTaskStatus(@PathVariable Long taskId, Authentication authentication) {
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        Long userId = loginUser.getUser().getId();
//        UserDTO userDTO = userMapper.selectUserInfoById(userId);
//        String userRole = userDTO.getUserRole();
//        if (!Objects.equals(userRole, "项目负责人") && taskService.taskIdUserIdExisits(taskId, userId)) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("不可以提交别人的任务");
//        }
//        boolean isUpdated = taskService.updateTaskStatus(taskId);
//        return isUpdated ? ResponseEntity.ok("任务状态更新成功！") : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务状态更新失败。");
//    }

    /**
     * 获取项目成员列表
     *
     * @param projectId 项目ID
     * @return 项目成员列表
     */
    @GetMapping("/project/{projectId}/members")
    public List<MemberDTO> getProjectMembers(@PathVariable Long projectId) {
        return taskService.getProjectMembers(projectId);
    }

    /**
     * 删除任务
     *
     * @param taskId 任务ID
     * @param authentication
     * @return 删除任务结果
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @DeleteMapping("/remove/{taskId}")
    public ResponseEntity<String> deleteTask(@PathVariable Long taskId, Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        UserDTO userDTO = userMapper.selectUserInfoById(userId);
        String userRole = userDTO.getUserRole();
        if (!Objects.equals(userRole, "项目负责人") && taskService.taskIdUserIdExisits(taskId, userId)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("不可以删除别人的任务");
        }
        boolean isDeleted = taskService.deleteTask(taskId);
        return isDeleted ? ResponseEntity.ok("任务删除成功！") : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务删除失败。");
    }

    @PreAuthorize("hasAnyAuthority('perm_leader')")
    @GetMapping("/{taskId}")
    public Task getTaskById(@PathVariable Long taskId){
        return taskService.getTaskById(taskId);
    }





    @PostMapping("/notify")
    public ResponseResult notifyProjectMembers(Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        return taskService.notifyProjectMembers(userId);
    }
}
